<template>
  <div class="use-history" @mousedown.stop="" @mousemove.stop="">
    <div class="title">经常访问</div>
    <div class="apps">
      <swiper v-if="history.length > 0" :modules="[Navigation, Mousewheel]" :slides-per-view="'auto'"
        :touchStartPreventDefault="false" style="padding: 0 40px;" mousewheel>
        <swiper-slide v-for="(item, index) in history" :key="index"
          style="width: auto;padding: 8px;box-sizing: border-box;" @move.stop="moveEvent" @moved.stop="movedEvent">
          <VTooltip>
            <a-component class="history-item" @click.stop="openUrl(item.url)" :border="false"
              @contextmenu.prevent.stop="showContextMenu($event, index)">
              <div class="app">
                <img class="u-icon" v-if="!item.appUrl" :src="iconSvg" alt="" />
                <img class="u-icon" v-else :src="item.appUrl" alt="" @error="handleImgError($event)" />
              </div>
            </a-component>

            <template #popper>
              <div>
                {{ item.title }}
              </div>
              <div style="color: var(--font-second-color);">
                {{ item.key }}
              </div>
            </template>
          </VTooltip>
        </swiper-slide>
      </swiper>
      <div v-else class="empty">暂无数据</div>
    </div>

    <teleport to="body">
      <!-- 右键菜单 -->
      <transition name="a-dialog-fade">
        <div v-if="contextMenu.visible" class="context-menu"
          :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }" @click.stop>
          <ul class="menu-list">
            <li class="item error" @click="onMenuDeleteAction">删除</li>
          </ul>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import AComponent from "@/home/common/a-component.vue";
import { ref, onMounted, onUnmounted, watch, reactive } from 'vue';
import { Navigation, Mousewheel } from 'swiper/modules'; // 引入 Mousewheel 模块
import { Swiper, SwiperSlide } from 'swiper/vue';
import { storage } from "@/lib/storage";
import { useToast } from 'vue-toastification'
import iconSvg from '/public/assets/app-logo/unknown.svg';

const toast = useToast()
const urlHistoryMap = ref({});
const history = ref([]);
const isDragging = ref(false);

const handleImgError = (event) => {
  event.target.src = iconSvg; // 设置为默认图片
};

const contextMenu = reactive({
  visible: false,
  x: 0,
  y: 0,
  index: -1,
});

// 移动事件
function moveEvent() {
  isDragging.value = true
}

// 移动结束事件
function movedEvent() {
  setTimeout(() => {
    isDragging.value = false
  }, 500)
}

// 打开 URL
function openUrl(url) {
  if (isDragging.value) {
    return
  }
  window.open(url)
}

const loadHistory = async () => {
  history.value = [];
  storage.get('urlHistory').then((data) => {
    if (!data) {
      return;
    }
    urlHistoryMap.value = data ? JSON.parse(data) : {};
    handlerMap();
  });
}

const handlerMap = () => {
  let us = [];
  for (let key in urlHistoryMap.value) {
    us.push(urlHistoryMap.value[key])
  }
  us.sort((a, b) => {
    if (b.count === a.count) {
      return b.time - a.time; // 按 time 降序
    }
    return b.count - a.count; // 按 count 降序
  })
  if (us.length > 30) {
    us = us.slice(0, 30)
  }
  us.forEach((item) => {
    urlHistoryMap.value[item.key] = {
      appUrl: item.appUrl,
      url: item.url,
      key: item.key,
      title: item.title,
      time: item.time,
      count: item.count
    }
  });
  history.value = us;
}

const onMenuDeleteAction = () => {
  if (contextMenu.index < 0) {
    return
  }
  let item = history.value[contextMenu.index];
  delete urlHistoryMap.value[item.key];
  storage.set('urlHistory', JSON.stringify(urlHistoryMap.value));
  history.value.splice(contextMenu.index, 1);
  toast.success('已删除');
  contextMenu.visible = false;
}


// 显示右键菜单
function showContextMenu(e, index) {
  contextMenu.x = Math.min(e.clientX, window.innerWidth - 140);
  contextMenu.y = Math.min(e.clientY, window.innerHeight - 100);
  contextMenu.index = index;
  contextMenu.visible = true;
}
const closeMenu = (e) => {
  contextMenu.visible = false;
  contextMenu.index = -1;
};

onMounted(async () => {
  loadHistory();
  // 添加全局点击事件监听器
  document.addEventListener('click', closeMenu);
})
// 在组件销毁时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('click', closeMenu);
});
</script>

<style scoped lang="less">
@import './use-history.less';
</style>